/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.worsik.android.test.rideshare.util.listener;

import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import cz.worsik.android.test.rideshare.constants.ViewConst;

public class NoAllPickOnClickListener implements CompoundButton.OnCheckedChangeListener
{
	View layout;

	public NoAllPickOnClickListener(View layout) {
		this.layout = layout;
	}
	
	public void onCheckedChanged(CompoundButton btn, boolean checked) {

		if (ViewConst.DEBUG) {
			Log.i("NO ALL PICK EVENT","Počet checkboxů: "+(ViewConst.CHECKBOX_COUNT));
		}
		CheckBox all = (CheckBox) layout.findViewById(ViewConst.CHECKBOX_START_ID);

		// zjistime stavy vsech checkboxu
		int[] zaskrtnute = new int[ViewConst.CHECKBOX_COUNT-1];
		int count = 0;

		for (int i=1; i<ViewConst.CHECKBOX_COUNT; i++)
		{
			if (ViewConst.DEBUG) {
				Log.i("NO ALL PICK EVENT","Vybírám checkbox "+(ViewConst.CHECKBOX_START_ID+i));
			}
			CheckBox ch = (CheckBox) layout.findViewById(ViewConst.CHECKBOX_START_ID+i);
			if (ch.isChecked())
			{
				zaskrtnute[count] = ch.getId();
				if (ViewConst.DEBUG) {
					Log.i("NO ALL PICK EVENT","Zaskrtnute("+count+") = "+ch.getId());
				}
				count ++;
			}
		}
		if (checked)
		{
			if (ViewConst.DEBUG) {
				Log.i("NO ALL PICK EVENT","Checked je TRUE");
			}
			// projdeme vsechny checkboxy a pokud jsou zaskrtnute, zaskrtneme i hlavni
			for (int i=0; i<zaskrtnute.length; i++)
			{
				if (ViewConst.DEBUG) {
					Log.i("NO ALL PICK EVENT","Zaskrtnute["+i+"] = "+zaskrtnute[i]);
				}
				if (zaskrtnute[i] <= 0)
				{
					if (ViewConst.DEBUG) {
						Log.i("NO ALL PICK EVENT","Zaskrtnute["+i+"] < 0  => RETURN");
					}
					return;
				}
			}
			all.setChecked(true);
		}
		else
		{
			if (ViewConst.DEBUG) {
				Log.i("NO ALL PICK EVENT","Checked je FALSE");
			}
			if (all.isChecked())
			{
				// zrusime vyber vsech
				all.setChecked(false);

				// nastavime zpet stavy
				for (int i=0; zaskrtnute[i] > 0; i++)
				{
					CheckBox ch = (CheckBox) layout.findViewById(zaskrtnute[i]);
					if (ch.getId() != btn.getId())
					{
						ch.setChecked(true);
					}
				}
			}
		}
	}
}
